import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import Cookies from 'js-cookie'

const getDefaultState = () => {
  return {
    userToken: getToken(),
    userId: Cookies.get('stu_id'),
    userName: Cookies.get('stu_name'),
    sex: Cookies.get('stu_sex'),
    age: Cookies.get('stu_age')
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },

  // 获取用户信息
  SAVE_USER_INFO(state, userInfo) {
    console.log('saving UserInfo to cookies...')
    Cookies.set('stu_id', userInfo.user_id)
    state.userId = userInfo.user_id
    Cookies.set('stu_name', userInfo.user_name)
    state.userName = userInfo.user_name
    Cookies.set('stu_sex', userInfo.sex)
    state.sex = userInfo.sex
    Cookies.set('stu_age', userInfo.age)
    state.age = userInfo.age
  }
}

const actions = {
  // 登录
  login({ commit }, user) {
    const data = {
      userUuid: user.username,
      password: user.password
    }
    return new Promise((resolve, reject) => {
      login(data)
        .then(response => {
          // 登录成功 => 保存token、保存用户名
          // 从返回结果里获取Token
          console.log('response', response)
          commit('SET_TOKEN', response.data.user_token)
          commit('SAVE_USER_INFO', response.data)
          setToken(response.data.user_token)
          resolve()
        })
        .catch(error => {
          console.error(error)
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          console.log('fake logout pass')
          removeToken() // must remove  token  first
          window.location.href = './' // 登出后重定向到首页，不过这个做法很简单粗暴
          resetRouter()
          commit('RESET_STATE')
          resolve()
        })
        .catch(error => {
          removeToken() // must remove  token  first
          window.location.href = './' // 登出后重定向到首页，不过这个做法很简单粗暴
          resetRouter()
          commit('RESET_STATE')
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
